package com.gaoyuzhe.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <code>@SentinelResource</code>相关的测试
 * @see com.alibaba.csp.sentinel.annotation.SentinelResource
 * @author gaoyuzhe
 */
@RestController
@RequestMapping("/sentinel/resource")
public class SentinelResourceController {
    public static final String ERROR_ID = "2";
    /**
     * 只配置了blockHandler
     * @return
     * @param id
     */
    @GetMapping("onlyBlockException/{id}")
    @SentinelResource(value="onlyBlockException",blockHandler = "onlyBlockExceptionHandler")
    public String onlyBlockException(@PathVariable("id") String id){
        if(ERROR_ID.equals(id)){
            throw new IllegalArgumentException("sorry , id error");
        }
        return "onlyBlockException 测试OK";
    }
    /**
     * 为onlyBlockException限流异常的回调
     * @return
     */
    public String onlyBlockExceptionHandler(String id, BlockException blockException){
        return "onlyBlockExceptionHandler" + "id :"+ id +",blockException:"+blockException.getClass();
    }

    /**
     * 只配置了fallback
     * @return
     */
    @GetMapping("onlyFallback/{id}")
    @SentinelResource(value = "onlyFallback",fallback = "onlyFallbackHandler")
    public String onlyFallback(@PathVariable("id") String id){
        if(ERROR_ID.equals(id)){
            throw new IllegalArgumentException("sorry , id error");
        }
        return "onlyFallback 测试OK";
    }
    /**
     * 为onlyFallback的运行时异常的回调
     * @return
     */
    public String onlyFallbackHandler(String id){
        return "onlyFallbackHandler" + "id :"+ id ;
    }

    /**
     * 同时配置了blockHandler和fallback
     * @return
     */
    @GetMapping("blockExceptionAndFallback/{id}")
    @SentinelResource(value = "blockExceptionAndFallback",
            blockHandler = "blockExceptionHandler",
            fallback = "fallBackHandler")
    public String blockExceptionAndFallback(@PathVariable("id") String id){
        if(ERROR_ID.equals(id)){
            throw new IllegalArgumentException("sorry , id error");
        }
        return "blockExceptionAndFallback 测试OK";
    }

    public String blockExceptionHandler(String id,BlockException blockException){
        return "blockExceptionHandler" + "id :"+ id +",blockException:"+blockException.getClass();
    }

    public String fallBackHandler(String id){
        return "fallBackHandler" + "id :"+ id ;
    }
}
